<template>
    <div class="box">
        <div class="title center">{{ props.name }}</div>
        <div :id="name" :style="{'padding':'10px','height': chartHeight,'width':chartWidth}"></div>
    </div>
</template>

<script setup>
import { defineProps, onMounted, watch, ref } from 'vue'
import * as echarts from 'echarts';

const props = defineProps({
    option: {
        type: Object,
        required: true
    },
    name: {
        type: String,
    },
    chartWidth:{
        type: String,
        default: '100%',
    },
    chartHeight: {
        type: String,
        default: '100%'
    }
})

// 存储图表实例的引用
const chartInstance = ref(null);

onMounted(() => {
    const chartDom = document.getElementById(props.name);
    // 清除Echarts默认添加的属性
    chartDom.removeAttribute("_echarts_instance_");

    chartInstance.value = echarts.init(chartDom);
    chartInstance.value.setOption(props.option);
})

// 添加watch监听option的变化
watch(() => props.option, (newOption) => {
    if (chartInstance.value) {
        // 清除之前的图表实例
        chartInstance.value.dispose();
        
        const chartDom = document.getElementById(props.name);
        chartDom.removeAttribute("_echarts_instance_");
        
        // 重新初始化图表并设置新的option
        chartInstance.value = echarts.init(chartDom);
        chartInstance.value.setOption(newOption);
    }
}, { deep: true });
</script>

<style scoped lang="scss">
.center {
    display: flex;
    justify-content: center;
    align-items: center;
}

.box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
}

.title {
    width: 90%;
    font-size: 40px;
    background-color: rgb(129, 66, 158);
    border-radius: 10px;
    margin: 10px auto;
    padding: 10px;
    color: white;
}

</style>